import AVFoundation
import Foundation

class AudioPlayerManager {
    // 单例模式，方便全局使用
    static let shared = AudioPlayerManager()
    
    private var queuePlayer: AVQueuePlayer?
    private var looper: AVPlayerLooper?
    private var playerItem: AVPlayerItem?
    private var playing = false
    
    // 播放结束的回调
    var onPlaybackFinished: (() -> Void)?
    
    private init() {} // 私有化初始化方法，确保单例
    
    //播放本地
    func playLocal(forResource name: String?, ofType ext: String?, looper: Bool = false) {
        let path = Bundle.main.path(forResource: name, ofType: ext)!
        let url = URL(fileURLWithPath: path)
        playAudio(from: url, isLooper: looper)
    }
    
    //播放data
    func playData(from date: Data, isLooper: Bool = false) {
        // 1. 将 Data 写入临时文件
        let tempFileURL = FileManager.default.temporaryDirectory
            .appendingPathComponent(UUID().uuidString)
            .appendingPathExtension("mp3") // 根据实际音频格式修改后缀
        
        do {
            try date.write(to: tempFileURL)
        } catch {
            showLog("写入临时文件失败: \(error)")
            return
        }
        let asset = AVAsset(url: tempFileURL)
        let playerItem = AVPlayerItem(asset: asset)
        playAudio(from: playerItem, isLooper: isLooper)
    }
    
    //播放网络
    func playUrl(from url: String, looper: Bool = false) {
        playAudio(from: URL(string: url)!, isLooper: looper)
    }
    
    //播放网络
    func playAudio(from url: URL, isLooper: Bool = false) {
        let playerItem = AVPlayerItem(url: url)
        playAudio(from: playerItem, isLooper: isLooper)
    }
    
    // 加载并播放音频
    func playAudio(from mPlayerItem: AVPlayerItem, isLooper: Bool = false) {
        configureAudioSession() // 确保每次播放前激活会话
        // 清理之前的播放器
        resetPlayer()
        
        // 创建 AVPlayerItem
        playerItem = mPlayerItem
        
        // 创建 AVPlayer
        if let playerItem = playerItem {
            queuePlayer = AVQueuePlayer(items: [playerItem])
            if isLooper {
                looper = AVPlayerLooper(player: queuePlayer!, templateItem: playerItem)
            }
        }
        queuePlayer?.play()
        // 监听播放结束
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(playerDidFinishPlaying),
            name: .AVPlayerItemDidPlayToEndTime,
            object: playerItem
        )
        
        // 开始播放
        queuePlayer?.play()
        playing = true
    }
    
    // 新增：配置音频会话
      private func configureAudioSession() {
          do {
              // 设置为 playback 模式（静音模式下仍可播放）
              try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
              try AVAudioSession.sharedInstance().setActive(true)
          } catch {
              showLog("音频会话配置失败: \(error)")
          }
      }
    
    // 暂停播放
    func pause() {
        queuePlayer?.pause()
        playing = false // 播放已暂停
    }
    
    // 继续播放
    func resume() {
        queuePlayer?.play()
    }
    
    // 跳转到指定时间
    func seek(to time: TimeInterval) {
        let cmTime = CMTime(seconds: time, preferredTimescale: 1)
        queuePlayer?.seek(to: cmTime)
    }
    
    // 获取当前播放时间
    func currentTime() -> TimeInterval {
        return queuePlayer?.currentTime().seconds ?? 0
    }
    
    // 获取音频总时长
    func duration() -> TimeInterval {
        return queuePlayer?.currentItem?.duration.seconds ?? 0
    }
    
    func isPlaying() -> Bool {
        return playing
    }
    
    // 清理播放器
    private func resetPlayer() {
        if let playerItem = playerItem {
            NotificationCenter.default.removeObserver(
                self,
                name: .AVPlayerItemDidPlayToEndTime,
                object: playerItem
            )
        }
        queuePlayer?.pause()
        queuePlayer = nil
        playerItem = nil
        playing = false
    }
    
    // 播放结束的回调
    @objc private func playerDidFinishPlaying() {
        playing = false
        onPlaybackFinished?()
    }
    
    // 释放资源
    deinit {
        resetPlayer()
    }
}
